
#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
     #   self.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1","Tipo":"Italiano","Calle":"lacalle"}]



    def _process(self):
	 pass
class MyOrganization(Bureaucracy.Bureaucracy):
    def _process(self):
	    time.sleep(2000)

class MyUnit(Unit.Hierarchy):
    def onStart(self):
        time.sleep(10)
        template = Behaviour.ACLTemplate()
        template.setProperty("from",self.name)
        template.setPerformative("inform")
        template.setOntology("spade:x:unit")
        t = Behaviour.MessageTemplate(template)
        self.gotoBehaviour=self.GotoBehaviour(self)
        self.myAgent.addBehaviour(self.gotoBehaviour, t)

    class GotoBehaviour(Behaviour.Behaviour):
        def __init__(self,unit):
            self.unit=unit
            Behaviour.Behaviour.__init__(self)

        def _process(self):
            m= self._receive(True)
            if m and m.getProperty("from")==self.unit.name:
                print "Dentro de la unidad:"+self.unit.name
                unitName=m.getContent().split(":")[1]
                u=MyUnit(self.myAgent, nick=self.myAgent.nick, password="pass", name=unitName)
                print "Tratando de entrar en "+unitName
                d=[{"name":"rol","value":"fuentes de informacion"}]
                entry=self.unit.requestEntryUnit(unitName,d)
                self.unit.joinUnit(u)
                self.myAgent.removeBehaviour(self)

    def _process(self):
            print "Dentro de la unidad:"+self.name
            mens=self.receiveMessage()
            while not mens and self.state!="unavailable":
              mens=self.receiveMessage()
              time.sleep(1)
            content=[]
            if mens:
                print mens
                for i in self.myAgent.info:
                    recurso=mens.getContent().split(":")[0]
                    tipo=mens.getContent().split(":")[1]
                    print recurso,tipo
                    if i["Tipo"]==tipo and recurso==i["Recurso"]:
                        content.append(i)
                if content!=[]:
                    ans=ACLMessage.ACLMessage()
                    ans.setPerformative("inform")
                    ans.setSender(self.myAgent.getAID())
                    ans.addReceiver(mens.getSender())
                    ans.setContent(str(content))
                    self.sendPrivateMessage(ans,mens.getSender().getName())



if __name__ == "__main__":
    a="sitea"
    for n in xrange(1,30):
        agent = a+str(n)+"@apolo.dsic.upv.es"
        #agent = "agent@thx1138.dsic.upv.es"
        #agent = "agent@tatooine.dsic.upv.es"
        b = Example(agent,"pasword")
        b.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1"+str(n),"Tipo":"Italiano","Calle":"lacalleA"+str(n)},{"Recurso":"Restaurant","Nombre":"Restaurante1"+str(n),"Tipo":"Japones","Calle":"lacalleA"+str(n)},{"Recurso":"Restaurant","Nombre":"Restaurante1"+str(n),"Tipo":"Chino","Calle":"lacalleA"+str(n)}]
        b.nick=nick="fuenteA"+str(n)
        b.start()
        print "Agent "+agent+" registering"
        time.sleep(2)
        lista= b.getOrganizationList()
        print lista
        for i in lista:
            goal=b.getOrganizationInfo(i)["goal"]
            g=eval(goal)
            if g.has_key("necesita") and g["necesita"]=="fuentes de informacion turistica":
                o=MyOrganization(b,nick="fuenteA"+str(n), name=i)
                b.joinOrganization(o)
                l=o.getUnitList()
                print l
                for u in l:
                    info=o.getUnitInfo(u)
                    if info["type"]=="Hierarchy" and eval(info["goal"])["necesita"]=="fuentes de informacion":
                        unit=MyUnit(b, nick="fuenteA"+str(n), password="pass", name=u)
                        d=[{"name":"rol","value":"fuentes de informacion"}]
                        entry=o.requestEntryUnit(u,d)
                        if not entry:
                            entry=o.requestEntryUnit(u,d)
                        if entry:
                            o.joinUnit(unit)







